package com.nowcoder.community.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nowcoder.community.entity.*;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.service.impl.CommentServiceImpl;
import com.nowcoder.community.service.impl.DiscussPostServiceImpl;
import com.nowcoder.community.service.impl.LikeServiceImpl;
import com.nowcoder.community.service.impl.UserServiceImpl;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ChenJH
 * @since 2022-12-26
 */
@Controller
//@RequestMapping("/discuss-post")
public class DiscussPostController implements CommunityConstant {
    @Autowired
    DiscussPostServiceImpl discussPostService;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    CommentServiceImpl commentService;
    @Autowired
    LikeServiceImpl likeService;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping(path = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, PageEntity pageEntity,
                                @RequestParam(name= "orderMode",defaultValue = "0") int orderMode) {
//        方法调用前 springmvc会自动实例化model 和pageentity 并将pageentity注入model
//        所以在thymeleaaf中也可以直接访问pageentity对象中的数据
//        LambdaQueryWrapper<DiscussPost> wrapper = new LambdaQueryWrapper<DiscussPost>();
////        discussPostLambdaQueryWrapper.eq(DiscussPost::getUserId, 111);
//        wrapper.orderByDesc(DiscussPost::getCreateTime);
//        wrapper.ne(DiscussPost::getStatus, 2);
//        Page<DiscussPost> page = discussPostService.page(pageEntity.toPage(), wrapper);

        Page<DiscussPost> page = discussPostService.getDiscussPosts(0,pageEntity, orderMode);

        long num = page.getPages();

        List<Map<String, Object>> discussPosts = new ArrayList<>();

        List<DiscussPost> records = page.getRecords();
        if (records != null) {
            for (DiscussPost discussPost : records) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("post", discussPost);
                User byId = userService.getById(discussPost.getUserId());
                map.put("user", byId);

//                点赞数
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);

        model.addAttribute("orderMode",orderMode);

//        需要封装的内容
        model.addAttribute("page", page);
        long from = page.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = page.getCurrent() + 2;
        to = Math.min(to, page.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/index?orderMode="+orderMode);
        return "/index";
    }

    @RequestMapping(path = "/discuss/detail/{discussPostId}", method = RequestMethod.GET)
    public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, PageEntity pageEntity) {
//帖子
        DiscussPost post = discussPostService.getById(discussPostId);
        model.addAttribute("post", post);
//        作者
        User user = userService.getById(post.getUserId());
        model.addAttribute(user);
//        点赞
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeCount", likeCount);
//        没登录 就相当于没点赞
        int likeStatus = hostHolder.getUser() == null ? 0 : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, discussPostId);
        model.addAttribute("likeStatus", likeStatus);

//      评论分页信息
        pageEntity.setSize(5);
        Page<Comment> page = commentService.findCommentsByEntity(ENTITY_TYPE_POST, post.getId(), pageEntity);
        //      评论：给帖子的评论
//       回复：给评论的评论
//       评论列表
        List<Comment> commentList = page.getRecords();
//      评论vo列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                HashMap<String, Object> commentVo = new HashMap<>();
//                评论
                commentVo.put("comment", comment);
//                作者
                commentVo.put("user", userService.getById(comment.getUserId()));
                //        点赞
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
//        没登录 就相当于没点赞
                likeStatus = hostHolder.getUser() == null ? 0 : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

//                回复列表
                Page<Comment> page2 = commentService.findCommentsByEntity(ENTITY_TYPE_COMMENT, comment.getId(), new PageEntity(1, Integer.MAX_VALUE));
                List<Comment> replyList = page2.getRecords();
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        HashMap<String, Object> replyVo = new HashMap<>();
                        replyVo.put("reply", reply);
                        replyVo.put("user", userService.getById(reply.getUserId()));
//                        回复目标
                        User target = (reply.getTargetId() == null || reply.getTargetId() == 0) ?
                                null : userService.getById(reply.getTargetId());
                        //        点赞
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
//        没登录 就相当于没点赞
                        likeStatus = hostHolder.getUser() == null ? 0 : likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);

                        replyVo.put("target", target);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);
//                回复数量
                long replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);
                commentVoList.add(commentVo);
            }
        }
        model.addAttribute("comments", commentVoList);

        //        需要封装的内容
        model.addAttribute("page", page);
        long from = page.getCurrent() - 2;
        from = from < 1 ? 1 : from;
        long to = page.getCurrent() + 2;
        to = Math.min(to, page.getPages());
        model.addAttribute("from", from);
        model.addAttribute("to", to);
        model.addAttribute("path", "/discuss/detail/" + discussPostId);
        return "/site/discuss-detail";
    }

    @RequestMapping(path = "/discuss/add", method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user = hostHolder.getUser();
        if (user == null) {
            return CommunityUtil.getJsonString(403, "你还没登录");
        }
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId().toString());
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(LocalDateTime.now());
        discussPostService.addDiscussPost(post);
//        储发 发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityId(post.getId())
                .setEntityType(ENTITY_TYPE_POST);
        eventProducer.fireEvent(event);

//        计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey,post.getId());


//        报错的情况 将来统一处理
        return CommunityUtil.getJsonString(0, "发布成功");
    }


    /**
     * 置顶 或取消置顶
     */
    @RequestMapping(path = "/discuss/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id) {

        Integer type = discussPostService.getById(id).getType();
//        转换状态
        if (type == 0) {
            type = 1;
        } else {
            type = 0;
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("type", type);

        discussPostService.updateType(id, type);
        //        储发 发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(id)
                .setEntityType(ENTITY_TYPE_POST);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJsonString(0,null,map);
    }

    /**
     * 加精 或取消
     */
    @RequestMapping(path = "/discuss/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {

        Integer status = discussPostService.getById(id).getStatus();
//        转换状态
        if (status == 0) {
            status = 1;
        } else {
            status = 0;
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("status", status);

        discussPostService.updateStatus(id, status);
        //        储发 发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(id)
                .setEntityType(ENTITY_TYPE_POST);
        eventProducer.fireEvent(event);

        //        计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey,id);

        return CommunityUtil.getJsonString(0,null,map);
    }

    /**
     * 拉黑
     */
    @RequestMapping(path = "/discuss/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);
        //        储发 删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityId(id)
                .setEntityType(ENTITY_TYPE_POST);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJsonString(0);
    }

}
